#include "toy_persistence.h"
#include <fstream>
#include <sstream>

ToyPersistence::ToyPersistence(const std::string& filename) : filename(filename) {}

std::vector<Toy> ToyPersistence::loadToys() {
    std::vector<Toy> toys;
    std::ifstream infile(filename);
    std::string line;
    while (std::getline(infile, line)) {
        std::stringstream ss(line);
        std::string item;
        std::vector<std::string> fields;
        while (std::getline(ss, item, ',')) {
            fields.push_back(item);
        }
        if (fields.size() == 6) {
            int id = std::stoi(fields[0]);
            std::string name = fields[1];
            std::string type = fields[2];
            double price = std::stod(fields[3]);
            int total = std::stoi(fields[4]);
            int available = std::stoi(fields[5]);
            toys.emplace_back(id, name, type, price, total, available);
        }
    }
    return toys;
}

void ToyPersistence::saveToys(const std::vector<Toy>& toys) {
    std::ofstream outfile(filename, std::ios::trunc);
    for (const auto& toy : toys) {
        outfile << toy.serialize() << std::endl;
    }
}    